<script lang="ts" setup>
import {ref} from 'vue'
import {ElMessage} from 'element-plus'
import * as FodConfigApi from '@/api/promotion/newcustomer/FodConfigApi'
import {fenToYuan, yuanToFen} from "@/utils";

interface DiscountRule {
  amount: number
  amountYuan: number
  discount: number
}

const discountRules = ref<DiscountRule[]>([])

onMounted(async () => {
  const rules = await FodConfigApi.read();
  rules.forEach((rule: DiscountRule) => {
    rule.amountYuan = fenToYuan(rule.amount) as unknown as number
  })
  discountRules.value = rules
})

const validateAll = (): boolean => {
  // 检查是否有金额小于等于0
  const hasInvalidAmount = discountRules.value.some(rule => rule.amountYuan <= 0)
  if (hasInvalidAmount) {
    ElMessage.error('所有金额必须大于0')
    return false
  }
  // 检查是否有重复金额
  const amounts = discountRules.value.map(rule => rule.amountYuan)
  const uniqueAmounts = new Set(amounts)
  if (amounts.length !== uniqueAmounts.size) {
    ElMessage.error('金额不能重复')
    return false
  }
  // 检查是否有折扣小于等于0
  const hasInvalidDiscount = discountRules.value.some(rule => rule.discount <= 0)
  if (hasInvalidDiscount) {
    ElMessage.error('所有折扣必须大于0')
    return false
  }
  return true
}

const addRule = async () => {
  const zeroAmountExists = discountRules.value.some(rule => rule.amountYuan == 0)
  if (zeroAmountExists) {
    ElMessage.warning('已存在未设置金额的规则，请先设置金额')
    return
  }
  if (!validateAll()) {
    return;
  }
  discountRules.value.push({
    amount: 0, // 初始值为0，用户需要修改
    amountYuan: 0.00,
    discount: 10
  })
}

const removeRule = async (index: number) => {
  if (discountRules.value.length <= 1) {
    ElMessage.warning('至少保留一条规则')
    return
  }
  discountRules.value.splice(index, 1)
  if (!validateAll()) {
    return;
  }
  await save();
}

// 监听单个规则的变化
const handleItemChange = async (_value: any) => {
  if (!validateAll()) {
    return;
  }
  await save();
}

const save = async () => {
  // 按金额升序排列
  const sortedDiscountRules = [...discountRules.value].sort((a, b) => {
    if (!a.amount || !b.amount) {
      return 0
    }
    if (a.amount === b.amount) {
      return a.discount - b.discount
    }
    return a.amount - b.amount
  })
  sortedDiscountRules.forEach((rule) => {
    rule.amount = yuanToFen(rule.amountYuan)
  })
  await FodConfigApi.write(sortedDiscountRules)
}
</script>

<template>
  <div v-hasRole="['shop_admin']" class="flex flex-col">
    <div
      class="mb-10px"
      v-for="(rule, index) in discountRules"
      :key="index"
    >
      <el-card shadow="hover" class="rule-card">
        <div class="flex items-center gap-15px">
          <span class="w-80px">规则 {{ index + 1 }}</span>

          <el-form
            :model="rule"
            label-width="80px"
            inline>
            <el-form-item>
              <el-input-number
                v-model="rule.amountYuan"
                :min="0"
                :max="9999"
                controls-position="right"
                size="small"
                placeholder="?"
                @change="handleItemChange"
              >
                <template #prefix>满</template>
                <template #suffix>元</template>
              </el-input-number>
            </el-form-item>
            <el-form-item>
              <el-input-number
                v-model="rule.discount"
                :min="0"
                :max="10"
                :step="0.1"
                controls-position="right"
                size="small"
                placeholder="?"
                @change="handleItemChange"
              >
                <template #prefix>打</template>
                <template #suffix>折</template>
              </el-input-number>
            </el-form-item>
          </el-form>

          <el-button
            type="danger"
            plain
            @click="removeRule(index)"
          >删除
          </el-button>
          <el-button
            v-if="index === discountRules.length - 1"
            type="primary"
            plain
            @click="addRule">
            添加规则
          </el-button>
        </div>
      </el-card>
    </div>
  </div>
  <div v-hasRole="['super_admin', 'platform_admin', 'tenant_admin']">
    还未实现对商家配置的访问
  </div>
</template>

<style scoped lang="scss">
.rule-card {
  :deep(.el-form-item) {
    margin-bottom: 0;
  }
}
</style>
